package davel

import (
	"net/http"
	"time"
)

type DavelHandler struct {
	davelApp *DavelApp
}

func (this *DavelHandler) Init(davelApp *DavelApp) {
	this.davelApp = davelApp
}

func (this *DavelHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			this.davelApp.DavelLog.Write("Recovered in ServeHTTP")
		}
	}()

	this.davelApp.DavelLog.Write(r.URL.Path)
	if r.URL.Path == "/sleep" {
		time.Sleep(10 * time.Second)
		rw.Write([]byte("sleep"))
	} else if r.URL.Path=="/bye" {
		err := this.davelApp.server.Shutdown(nil)
		if err != nil {
			this.davelApp.DavelLog.Write("shutdown the server err" + err.Error())
		}
	} else {
		rw.Write([]byte(r.URL.Host))
		rw.Write([]byte(r.URL.Port()))
		rw.Write([]byte(r.URL.Path))
	}
}